#define _CRT_SECURE_NO_WARNINGS 1
class Solution {

public:
    int find(int x, vector<int>& p) {
        if (x != p[x]) x = find(p[x], p);
        return x;
    }
    long long countPairs(int n, vector<vector<int>>& edges) {
        vector<int> p(n + 1);
        vector<int> sm(n + 1);
        for (int i = 0; i <= n; i++) {
            p[i] = i;
            sm[i] = 1;
        }

        for (auto it : edges) {     
            int a = it[0];
            int b = it[1];
            int x = find(a, p);
            int y = find(b, p);
            if (x != y) {
                p[y] = x;
                sm[x] += sm[y];
            }
        }
        long long ans = 0;
        for (int i = 0; i < n; i++) {
            if (p[i] == i) {
                ans += ((long long)sm[i] * (n - sm[i]));
            }
        }
        return ans / 2;
    }
};